<!--
    -  Copyright (c) 2018-2025, haohanwork.com All rights reserved.
  -->
<template>
    <div class="execution">
        <basic-container>
            <h2 class="">
                基础信息
            </h2>
            <el-form ref="form" class="purchasePlanFrom" :inline="true" :model="purchaseOrder" label-width="120px">
                <el-form-item label="采购类型">
                    <el-radio-group v-model="purchaseOrder.methodType">
                        <el-radio :label="2">平台直采</el-radio>
                        <el-radio :label="3">协议采购</el-radio>
                        <el-radio :label="1">竞价采购</el-radio>
                    </el-radio-group>
                </el-form-item>
                <br/>
                <br>
                <el-form-item label="是否审核">
                    <el-radio-group v-model="purchaseOrder.reviewType">
                        <el-radio :label="2">是</el-radio>
                        <el-radio :label="1">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="选择审核总监" v-if="purchaseOrder.reviewType == 2">
                  <el-select v-model="transactorId" placeholder="选择审核总监" @change="getSup">
                    <el-option v-for="item in supList" :label="item.name" :value="item.id" :key="index"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="采购截止时间">
                    <el-date-picker type="datetime" value-format="yyyy-MM-dd HH:mm:ss" v-model="purchaseOrder.buyFinalTime" placeholder="选择日期时间"></el-date-picker>
                </el-form-item>
            </el-form>
        </basic-container>

        <basic-container>
            <h2>采购单商品列表</h2>
            <el-form :inline="true" class="pocForm" label-width="90px" :model="purchaseOrder">
                <!--<el-form-item label="商品">-->
                    <!--<el-input v-model="purchaseOrder.goods" placeholder="请输入商品名称/编码/条形码"></el-input>-->
                <!--</el-form-item>-->
                <!--<el-button class="checkGoods" type="text" @click="dialogFormVisible = true">查看所有商品&nbsp;</el-button>-->

                <el-form-item label="商品名称:" prop="goodsName" label-width="100px">
                    <el-select
                            clearable
                            filterable
                            default-first-option
                            v-model="selectGoods.goodsName"
                            remote :remote-method="searchGoodsByName(selectGoods)"
                            :loading="selectGoods.loading"
                            @change="onGoodsSelectChange($event, selectGoods)"
                            placeholder="请输入商品名称">
                        <el-option
                                v-for="item in selectGoods.goodsList"
                                :key="item.id" :label="item.goodsName"
                                :value="item.id">
                        </el-option>
                    </el-select>
                    <el-button type="text" @click="showGoodsDialog()">所有商品</el-button>
                </el-form-item>

                <el-form-item label="规格:" prop="goodsId">
                    <el-select class="form-field"
                               v-model="selectGoods.goodsId"
                               @change="onModelSelectChange($event, selectGoods)"
                               placeholder="请选择">
                        <el-option
                                v-for="item in selectGoods.goodsModelList"
                                :key="item.id"
                                :label="item.modelName+' /单位:'+item.modelUnit"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>


                <el-form-item label="数量">
                    <el-input v-model="purchaseOrder.needBuyNum" v-enter-number type="number" oninput="if(value.length>8)value=value.slice(0,8)" class="form-field--small"  placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary"  @click="addSubmit(selectGoods,purchaseOrder.needBuyNum)">+添加</el-button>
                </el-form-item>
            </el-form>
            <!--商品列表表格-->
            <el-table :data="pocData" border style="width: 100%">
                <el-table-column label="商品图片" align="center" width="180">
                    <template slot-scope="scope">
                        <img :src="scope.row.goodsImg" height="50px"/>
                    </template>
                </el-table-column>
                <el-table-column prop="goodsName" label="商品名称" width="180"></el-table-column>
                <el-table-column prop="modelName" label="规格名称"></el-table-column>
                <el-table-column prop="unit" label="单位"></el-table-column>
                <el-table-column prop="marketPrice" label="下单单价（元）"></el-table-column>
                <el-table-column label="下单数量" prop="needBuyNum" align="center">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.needBuyNum" v-enter-number type="number" oninput="if(value.length>8)value=value.slice(0,8)" class="form-field--small" @change="countMoney()"/>
                    </template>
                </el-table-column>
                <el-table-column prop="goodsRemark" label="商品备注">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.goodsRemark"
                              class="form-field"
                              placeholder="" />
                  </template>
                </el-table-column>
                <el-table-column label="采购金额" prop="money" align="center">
                    <template slot-scope="scope">
                        {{(scope.row.marketPrice * scope.row.needBuyNum).toFixed(2)}}
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="120">
                    <template slot-scope="scope">
                        <el-button @click.native.prevent="deleteRow(scope.$index, tableData)" type="text" size="small">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="settle-accounts">
                <h3>合计金额:￥{{totalPrice.toFixed(2)}}</h3>
            </div>
        </basic-container>

        <basic-container>
            <el-form class="remarkForm" label-width="90px" :model="purchaseOrder">
                <el-form-item label="备注：">
                    <el-input type="textarea" v-model="remarks" :rows="5" placeholder="请输入内容"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button @click="close">取消</el-button>
                    <el-button type="primary" @click="onSubmit">提交采购单</el-button>
                </el-form-item>
            </el-form>
        </basic-container>

        <el-dialog title="选择商品" :visible.sync="dialogVisible">
            <goods-list-dialog @select="onSelectGoods" :buyerId="''"></goods-list-dialog>
        </el-dialog>
    </div>
</template>
<!-- 采购单 -->
<script>
    import {
        fetchList,
        queryList,
        addPurchaseOrderAndDetail
    } from '@/api/scm/purchase/purchase_order'
    import {
        tableOption
    } from '@/const/crud/scm/purchase/purchase_order'
    import {
        mapGetters
    } from 'vuex'
    import{
      fetchList as shList,
    } from "@/api/purchase/purchaseemployee";
    import Request from '../../../order/request.js'
    import {getStore, setStore} from "@/util/store";
    import goodsListDialog from '@/scm/order/customerOrder/components/goodsList.vue';
    import Util from '@/util/pds/utils';
    let cookieUtil = new Util();

    export default {
        name: 'addPlan',
        //商品规格id数组
        ids:[],
        dialogTableVisible: false,
        data() {
            return {
                request: new Request(),
                currentPage: 1,
                pageSize: 15,
                purchaseOrder: {
                    methodType: 2,
                    purchaseOrderType:1,
                    reviewType: 2,
                    buyFinalTime:'',
                    needBuyNum: '',
                    expensepre: '',
                    expenseName: '',
                    remark: ''
                },
                pocData: [],
                goodsList: [],
                form2: {
                    indexes: '',
                    region: '',
                    date1: '',
                    date2: '',
                    delivery: false,
                    type: [],
                    resource: '',
                    desc: ''
                },
                formLabelWidth: '120px',
                // 选择商品
                dialogVisible: false,
                selectGoods: {
                    goodsName: '',
                    loading: '',
                    goodsList: [],
                    goodsId: '',
                    goodsModelList: []
                },
                totalPrice:0.00,
                remarks:'',
                supList:[],
                transactorId:'',
                flag:1
            }
        },
        props:{
            buyerId: String
        },
        components: {
            goodsListDialog
        },
        computed: {
          ...mapGetters(['tagWel', 'tagList', 'tag', 'website']),
          tagLen() {
            return this.tagList.length || 0
          }
        },
        created() {
          this.getList();
        },
        methods: {
            //获取采购商总监
            getList() {
              let params = {
                purchaseEmployeeType: 1
              }
              shList(Object.assign({
                current:1,
                size: 20
              }, params)).then(response => {
                this.supList = response.data.data.records
              })
            },
            dialogTableVisible: {},
            deleteRow(index, rows) {
                this.pocData.splice(index, 1);
                this.totalPrice = 0;
                for(var i in this.pocData){
                  this.totalPrice += parseFloat(this.pocData[i].needBuyNum*this.pocData[i].marketPrice);
                }
            },
            onSubmit() {
                if(this.flag != 1){
                  return false;
                }
                if(this.purchaseOrder.buyFinalTime == ''){
                  this.$message.error("请选择时间");
                  return false;
                }
                if(this.pocData == []){
                  this.$message.error("请选择商品");
                  return false;
                }
                if(this.purchaseOrder.reviewType == 2){
                  if(this.transactorId == ''){
                    this.$message.error("请选择审核人");
                    return false;
                  }
                }
                let params = {
                    pmId: getStore({name: "pmId"}),
                    list:[],
                    methodType:this.purchaseOrder.methodType,
                    reviewType:this.purchaseOrder.reviewType,
                    buyFinalTime:this.purchaseOrder.buyFinalTime,
                    purchaseOrderType:'1',
                    remarks:this.remarks,
                    transactorId:this.transactorId
                };
                this.pocData.forEach(item =>{
                    let obj = {};
                    obj.goodsModelId = item.goodsId;
                    obj.needBuyNum = item.needBuyNum;
                    obj.remarks = item.goodsRemark;
                    params.list.push(obj)
                });
                for(var i in params.list){
                  if(params.list[i].needBuyNum == ''){
                    this.$message.error("请选择数量")
                    return false;
                  }
                }
                this.flag = 2;
                addPurchaseOrderAndDetail(params).then(res=>{
                    if(res.code=200){
                        this.$message.success("采购单生成成功");
                        let _this = this;
                        setTimeout(function () {
                          _this.close();
                        },2000)
                    }else{
                        this.flag = 1;
                        this.$message.error("采购单生成失败")
                    }
                });
            },
            //添加商品
            addSubmit(goods,num){
              console.log(goods);
              var good = {
                  goodsId:goods.goodsModelList[0].goodsId,
                  goodsImg: goods.thumbUrl,
                  goodsName: goods.goodsName,
                  unit: goods.goodsModelList[0].modelUnit,
                  marketPrice: goods.goodsModelList[0].modelPrice,
                  modelName:goods.goodsModelList[0].modelName,
                  needBuyNum: num,
                  goodsRemark: '',
              }
              this.pocData.push(good);
              this.totalPrice = 0;
              for(var i in this.pocData){
                this.totalPrice += parseFloat(this.pocData[i].needBuyNum*this.pocData[i].marketPrice);
              }
            },
            //改变input是计算
            countMoney(){
              this.totalPrice = 0;
              for(var i in this.pocData){
                this.totalPrice += parseFloat(this.pocData[i].needBuyNum*this.pocData[i].marketPrice);
              }
            },
            // 商品选择相关
            searchGoodsByName(row) {
                // 将row信息传入
                let _this = this;
                return function (searchValue) {
                    if (searchValue !== '') {
                        row.loading = true
                        console.log('time', searchValue);
                        let params = {
                            goodsName: searchValue,
                        }
                        params.buyerId = _this.buyerId;
                        params.shopId = getStore({name: "shopId"})
                        params.pageNo = _this.currentPage
                        params.pageSize = _this.pageSize
                        params.goodsName = searchValue
                        _this.request.getGoodsList(params).then(res => {
                            if (res.code == 200) {
                              _this.$set(row, 'goodsList', res.ext.list);
                              _this.$set(row, 'loading', false);
                              _this.goodsList = res.ext.list
                              _this.currentPage = res.ext.pageNo
                              _this.totalCount = res.ext.count
                            } else if (res.code == '983') {
                                _this.goodsList = []
                            } else {
                                _this.$message.error('请求失败')
                            }
                        })
                    }
                }
            },
            onGoodsSelectChange(e, row) {
                console.log("select");
                console.info("e", e);
                console.info("row" ,row);
                if(e){
                    let selectedGoods = row.goodsList.filter(item => item.id === e)[0]
                    row.goodsModelList = selectedGoods.goodsModelList
                    this.$set(row, 'goodsName', selectedGoods.goodsName)
                    this.$set(row, 'thumbUrl', selectedGoods.thumbUrl)
                    this.onModelSelectChange(selectedGoods.goodsModelList[0].id, row)
                    row.goodsModel = ''
                }else{
                    // 清空选项时
                    this.$set(row, 'goodsId', '');
                    row.goodsId = '';
                }
            },
            onModelSelectChange(e, row) {
                let selectedModel = row.goodsModelList.filter(item => item.id === e)[0]
                // this.$set(row, 'goodsId', selectedModel.id)
                // this.$set(row, 'purchasePrice', selectedModel.purchasePrice || selectedModel.modelPrice)
                // this.$set(row, 'goodsImg', selectedModel.modelUrl)
                // this.$set(row, 'goodsModel', selectedModel.modelName)
                // this.$set(row, 'unit', selectedModel.modelUnit)
                // this.$set(row, 'buyPrice', selectedModel.buyPrice)
            },
            showGoodsDialog() {
                this.dialogVisible = true
            },
            onSelectGoods(goods) {
                this.dialogVisible = false;
                this.selectGoods = goods;
                let orderItem = {
                    goodsName: goods.goodsName,
                    goodsModelList: goods.goodsModelList,
                    goodsList: [],
                    goodsNum: '',
                    remarks: '',
                    thumbUrl: goods.thumbUrl
                }
                this.onModelSelectChange(orderItem.goodsModelList[0].id, orderItem)
            },
            close(){
                var str_before = location.href.split('#')[1];
                let { tag, key } = this.findTag(str_before);
                this.$store.commit('DEL_TAG', tag);
                this.$router.go(-1);
            },
            findTag(value) {
              let tag, key
              this.tagList.map((item, index) => {
                if (item.value === value) {
                  tag = item
                  key = index
                }
              })
              return { tag: tag, key: key }
            }
        }
    }
</script>

<style lang="scss" scoped>
    .execution h2 {
        margin-bottom: 20px;
        &:nth-of-type(2) {
            margin-top: 20px;
        }
    }

    .checkGoods {
        &:hover {
            text-decoration: underline;
        }
        color: blue;
    }

    h3 {
        float: right;
    }
    .settle-accounts{
      padding: 10px 0;
      overflow: hidden;
    }
</style>
